package com.yuanshen.send;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.nio.charset.StandardCharsets;
import java.util.UUID;


/**
 * @author 朱厚强
 * @version 1.0
 * @classname DeadMessageExchange
 * 死信交换机测试
 */
@SpringBootTest
@Slf4j
public class DeadMessageExchange{
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Test
    public void testSendMessage2SimpleQueue() {
        // 交换机
        String exchange = "zhuhq.TOPIC";
        // 准备消息
        String message = "最美香山红叶，我们一起沐浴红色海洋！";

        // 准备CorrelationData
        // 消息ID
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        // 准备ConfirmCallback
        correlationData.getFuture().addCallback(result -> {
            // 判断结果
            if (result.isAck()) {
                // ACK
                log.info("消息成功投递到交换机！消息ID: {}", correlationData.getId());
            } else {
                // NACK
                log.error("消息投递到交换机失败！消息ID：{}", correlationData.getId());
                // 重发消息
            }
        }, ex -> {
            // 记录日志
            log.error("消息发送失败！", ex);
            // 重发消息
        });
        rabbitTemplate.convertAndSend(exchange, "sms.news", message, correlationData);
    }

    /**
     * 测试ttl
     */
    @Test
    public void testTTL(){
        //创建持久化消息
        Message message = MessageBuilder
                .withBody("hello ttl & dead-letter".getBytes(StandardCharsets.UTF_8))
                .setExpiration("5000") //设置消息5s过期
                .build();
        //准备消息的唯一ID
        CorrelationData correlationData = new
                CorrelationData(UUID.randomUUID().toString());
        //投递消息
        rabbitTemplate.convertAndSend("ttl.direct","ttl",message,correlationData);
    }
}
